﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Threading.Thread;
using static System.Console;

namespace Project_4
{
    /// <summary>
    /// 4.3 从任务中获取结果Task.Result
    /// </summary>
    public class Unit_4_03
    {
        public static void Go()
        {
            TaskMethod("主线程任务");
            Task<int> task = CreateTask("Task 1");
            task.Start();
            var result = task.Result;
            WriteLine($"Result is : {result}");

            task = CreateTask("Task 2");
            task.RunSynchronously();
            result = task.Result;
            WriteLine($"Result is : {result}");

            task = CreateTask("Task 3");
            WriteLine(task.Status);
            task.Start();

            while (!task.IsCompleted)
            {
                WriteLine(task.Status);
                Sleep(TimeSpan.FromSeconds(0.5));
            }

            WriteLine(task.Status);
            result = task.Result;
            WriteLine($"Result is : {result}");
        }

        static Task<int> CreateTask(string name)
        {
            return new Task<int>(()=>TaskMethod(name));
        }

        static int TaskMethod(string name)
        {
            WriteLine($"Task {name} is running on a thread id " +
                $"{CurrentThread.ManagedThreadId}. 是否是线程池的线程:" +
                $"{CurrentThread.IsThreadPoolThread}");
            Sleep(TimeSpan.FromSeconds(2));
            return 42;
        }
    }
}
